package com.gcb.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gcb.common.constant.Constants;
import com.gcb.common.core.domain.entity.GcbUser;
import com.gcb.common.core.domain.entity.SysUser;
import com.gcb.common.core.redis.RedisCache;
import com.gcb.common.enums.CommonStatusEnum;
import com.gcb.common.enums.DeleteFlagEnum;
import com.gcb.common.enums.VerifyCodeCacheKeyEnum;
import com.gcb.common.exception.ServiceException;
import com.gcb.common.utils.huawei.SmsUtils;
import com.gcb.dao.SysUserDao;
import com.gcb.service.ICommonService;
import com.gcb.service.IGcbUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CommonService implements ICommonService {

    @Resource
    private IGcbUserService gcbUserService;

    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private RedisCache redisCache;

    private void send(String mobile, VerifyCodeCacheKeyEnum key) {
        // 生成6位随机验证码
        String code = RandomUtil.randomNumbers(6);
        log.info("验证码：{}", code);
        redisCache.setCacheObject(key.getKey() + mobile, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        try {
            SmsUtils.sendSms(code, mobile);
        } catch (Exception e) {
            throw new ServiceException("发送短信验证码失败");
        }
    }

    @Override
    public void sendVerifyCode(String mobile, VerifyCodeCacheKeyEnum key) {
        Validator.validateNotEmpty(mobile, "手机号不可为空");
        Validator.validateMobile(mobile, "请输入正确手机号");

        if (VerifyCodeCacheKeyEnum.APP.equals(key)) {
            // 查询是否存在该用户
            GcbUser user = gcbUserService.getByMobile(mobile);
            Validator.validateNotNull(user, "该手机号未注册");
            Validator.validateNotEqual(DeleteFlagEnum.DELETED.getCode(), user.getDelFlag(), "该用户已被删除");
            Validator.validateNotEqual(CommonStatusEnum.STOP.getCode(), user.getStatus(), "该用户已被停用");
        } else {
            LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysUser::getPhonenumber, mobile);
            wrapper.select(SysUser::getDelFlag, SysUser::getStatus);
            SysUser user = sysUserDao.getOne(wrapper);
            Validator.validateNotNull(user, "该手机号未注册");
            Validator.validateNotEqual(DeleteFlagEnum.DELETED.getCode(), user.getDelFlag(), "该用户已被删除");
            Validator.validateNotEqual(CommonStatusEnum.STOP.getCode(), user.getStatus(), "该用户已被停用");
        }

        send(mobile, key);
    }

    @Override
    public void sendVerifyCodeWithoutRegCheck(String mobile, VerifyCodeCacheKeyEnum key) {
        Validator.validateNotEmpty(mobile, "手机号不可为空");
        Validator.validateMobile(mobile, "请输入正确手机号");
        send(mobile, key);
    }
}
